const express=require("express")
const uploadsfiles=express.Router();
const multer = require("multer")
var upload = multer({ dest: 'pub/' })
const path = require("path")
const fs=require("fs")
const moment = require('moment');
const localhost='http://49.235.166.90:5055/'
moment.locale('zh-cn');
const {recommendTable}=require('../database/filesbase');
const {recommendTable:userbase}=require("../database/userbase");

//最大六张图
uploadsfiles.post('/', upload.array('imgs1',6), function (req, res, next) {
    let imgList=[];
    // console.log(req.files);
    // console.log(req.body.id);
    // console.log(req.body.content);
    //图片和内容不能两个同时为空
    if(req.body.content||req.body.datetime){

        req.files.forEach((v,i)=>{    
            let file=v
            //获取后缀名
            let extname = path.extname(file.originalname)
            //获取上传成功之后的文件路径
            filepath = file.path
            //上传之后文件的名称
            filename = filepath + extname
            fs.renameSync(filepath,filename)
            imgList.push(`${localhost}${file.filename}${extname}`)
        })
        recommendTable.create({
            useID:req.body.id,
            dataTime:moment().format('YYYY-MM-DD HH:mm:ss'),
            imgUrl:imgList,
            content:req.body.content
        },()=>{
            // console.log('添加数据成功');
            
        })
        //向用户的数据表中添加动态数据
        userbase.findOne({useID:req.body.id},(err,data)=>{
           if(data){
                userbase.updateMany({useID:req.body.id},
                    {
                    $push:{
                        dynamicRecord:{
                            dataTime:moment().format('YYYY-MM-DD HH:mm:ss'), 
                            content:req.body.content,  
                            imgUrl:imgList
                        }
                    }
                },(err,raw)=>{
                    // console.log(raw);
                })
           }else{
               userbase.create({
                   useID:req.body.id,
                   dynamicRecord:[
                       {
                        dataTime:moment().format('YYYY-MM-DD HH:mm:ss'),   
                        content:req.body.content,
                        imgUrl:imgList
                       }
                   ]
               })
           }
        })
        res.send("sussess")
    }else{
        res.send("error:字段错误")
    }

  });

module.exports=uploadsfiles